package ace.tool.generate.code.impl.generator.graphql;

import ace.tool.generate.code.impl.generator.AbstractGenerator;
import ace.tool.generate.code.impl.generator.graphql.model.*;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;

/**
 * @author caspar
 * @date 2023/11/17 9:57 生成graphql schema file query 与 mutation 默认架构内容
 */
public class GraphqlSchemaGenerator
    extends AbstractGenerator<GraphqlSchemaGeneratorInput, GraphqlSchemaModel> {
  private static final String DTO_TYPE_SUFFIX = "";
  private static final String INPUT_TYPE_SUFFIX = "Input";
  private final GraphqlTemplateModelResolver resolver = new GraphqlTemplateModelResolver();

  @Override
  public void generate(List<GraphqlSchemaGeneratorInput> graphqlSchemaGeneratorInputs) {
    throw new RuntimeException("不支持批量,请使用单个生成接口");
  }

  @Override
  protected GraphqlSchemaModel resolveModel(GraphqlSchemaGeneratorInput input) {
    List<GraphqlSchemaModelField> fields =
        input.getParams().stream().map(this::resolveField).collect(Collectors.toList());

    return GraphqlSchemaModel.builder().fields(fields).build();
  }

  private GraphqlSchemaModelField resolveField(Class cls) {
    GraphqlTemplateModel graphqlTemplateModel = resolver.resolveModel(cls);

    String simpleClassName = graphqlTemplateModel.getName();

    String idType =
        graphqlTemplateModel.getFields().stream()
            .filter(p -> p.getIdFlag())
            .findFirst()
            .map(p -> p.getType())
            .orElse("");

    return GraphqlSchemaModelField.builder()
        .dtoModelName(simpleClassName + DTO_TYPE_SUFFIX)
        .inputModelName(simpleClassName + INPUT_TYPE_SUFFIX)
        .methodNamePrefix(StringUtils.uncapitalize(simpleClassName))
        .idType(idType)
        .build();
  }

  @Override
  protected String getFileName(GraphqlSchemaGeneratorInput input, GraphqlSchemaModel schemaModel) {
    return input.getOutputFileName();
  }
}
